<?php

namespace App\Console\Commands;

use App\Console\Base;
use common\enum\CommonEnum;
use App\Models\HallPartnerConfig;
use App\Models\MoneyPartner;
use Illuminate\Support\Facades\DB;
use App\Services\MoneyService;
use common\enum\MoneyExchangeEnum;

class CheckHallAPI extends Base
{
    /**
     * 控制台命令 signature 的名称。
     *
     * @var string
     */
    protected $signature = self::PREFIX . 'check_hall_api {--hall_id=}';

    /**
     * 控制台命令说明。
     *
     * @var string
     */
    protected $description = 'CheckHallAPI';

    /**
     * 执行控制台命令。
     *
     * @return mixed
     */
    public function handle()
    {
        $hallID = $this->option('hall_id');
        $invalidIDs = HallPartnerConfig::where(['hall_id' => $hallID])->where('status', '<>', CommonEnum::ENABLED)->distinct()->pluck('partner_id');

        $page = 1;
        $size = 1000;
        $mps = [];
        while (count($mps) == $size || $page === 1) {
            $mps = MoneyPartner::where(['hall_id' => $hallID])->where('balance', '>', 0)->whereIn('partner_id', $invalidIDs)->offset(($page - 1) * $size)->limit($size)->get();
            foreach ($mps as $mp) {
                $params = [
                    'hall_id' => $mp['hall_id'],
                    'user_id' => $mp['user_id'],
                    'partner_id' => $mp['partner_id'],
                    'amount' => $mp['balance'],
                    'type' => MoneyExchangeEnum::EXCHANGE_TYPE_P2M,
                    'remark' => '关闭API，系统自动转账',
                    'create_admin_id' => 0,
                    'is_manual' => 0,
                    'force' => true, // 强行模式
                ];
                // 转账
                MoneyService::exchange($params);
            }
            $page++;
        }
    }
}
